package healthyTool;

import java.io.*;
import java.util.*;
import gnu.io.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class SerialCommon implements Runnable, SerialPortEventListener{

	
	static CommPortIdentifier portId;
	  static Enumeration portList;//定义了从一个数据结构得到连续数据的手段
    public double temperature;
    public int[] BloodPressData = new int[2];
    public int[] OXYdata = new int[2];
    public int[] ECG = new int[10];
    
    SerialPort serialPort;//关于串口参数的静态成员变量类
    Thread readThread;
    
    public InputStream inputStream;//输入数据流
    
    public SerialCommon(){
    	System.out.println("串口初始化");
    	portList = CommPortIdentifier.getPortIdentifiers();
    	
    	while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            System.out.println("port*****" + portId.getName());
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                 if (portId.getName().equals("COM8")) {
               // if (portId.getName().equals("/dev/term/a")) {
                    System.out.println("COM4打开");
                }
            }
        }
    }
    
    public void OpenCom(){
    	try {
    		 serialPort = (SerialPort) portId.open("SerialCommon", 2000);//打开串口，两个参数，一个名称、一个延迟函数（毫秒）
        } catch (PortInUseException e) {}
        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {}
	try {
            serialPort.addEventListener(this);//添加串口监听
	} catch (TooManyListenersException e) {}
        serialPort.notifyOnDataAvailable(true);//设置串口有数据的事件TRUE有效
        try {
            serialPort.setSerialPortParams(57600,//设置串口参数依次为（波特率、数据位、停止位、奇偶校验）
                SerialPort.DATABITS_8,//数据位为8
                SerialPort.STOPBITS_1,//停止位为1
                SerialPort.PARITY_NONE);//无校验
        } catch (UnsupportedCommOperationException e) {}
        readThread = new Thread(this);
        readThread.start();
    }
    public void CloseCom(){
    	try{
    		serialPort.notifyOnDataAvailable(false);
    		serialPort.removeEventListener();
    		inputStream.close();
    		serialPort.close();
    	}
    	catch(Exception e){
    		e.printStackTrace();
    	}
    }
	@Override
	public void serialEvent(SerialPortEvent event) {
		// TODO Auto-generated method stub
		try{
    		Thread.sleep(500);
    	}catch(InterruptedException e){
    		e.printStackTrace();
    	}
        switch(event.getEventType()) {
        case SerialPortEvent.BI:
        case SerialPortEvent.OE:
        case SerialPortEvent.FE:
        case SerialPortEvent.PE:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
        case SerialPortEvent.DATA_AVAILABLE:
        	
           byte[] readBuffer = new byte[250];
           byte[] showBuffer = new byte[41];
           
            try {
                while (inputStream.available() > 0) {
                		int numbytes = inputStream.read(readBuffer);
               		System.out.println("读取从客户端得到的数据字节为："+ numbytes);
               		
                    if(numbytes % 41 == 0){
                    	int k = numbytes / 41;
                    	int j = 0;
                    	for(int i = 0; i < k; i++){
                    		System.arraycopy(readBuffer, j, showBuffer, 0, 41);
                    		showData(showBuffer);
                    		j = j + 41;
                    	}
                    }
                }
              //  System.out.println(new String(readBuffer));
            } catch (IOException e) {}
            break;
        }
	}

	
	public void showData(byte[] buffer){
    	if(buffer[24] == 37){
    		getTemperature(buffer);
				System.out.print("体温数据 = ");
			}
			if(buffer[24] == 17){
				getOXY(buffer);
				System.out.print("血氧脉搏数据 = ");
			}
			if(buffer[24] == 12){
				 getBooldPress(buffer);
				System.out.print("血压数据 = ");
			}
			if(buffer[14] == 2){
				getECG(buffer);
				System.out.print("心电数据 = ");
			}
		for(int i = 0; i < 41; i++){
			int k = buffer[i] & 0xFF;//将字节型数据转换成int型数据，防止负数的产生
			System.out.print( k +" ");
		}
		System.out.println();
    }
    public void getTemperature(byte[] buffer){
    	int temp1 = buffer[26] & 0x0FF;
    	int temp2 = buffer[27] & 0x0FF;
    	double temp3 = temp1 + temp2 * 256;
    	 temperature =  temp3 / 100 + 2.5;
    	System.out.println("体温为 ：  " + temperature);
  
    }
    
    public void getBooldPress(byte[] buffer){
    	
    	int highPress = buffer[26] & 0xFF;
    	int lowPress = buffer[28] & 0xFF;
    	if(highPress != 0 && lowPress != 0){
    		System.out.println("高压为：  " + highPress + "低压为：  " + lowPress + "************************************");
    	}
    	BloodPressData[0] = highPress;
    	BloodPressData[1] = lowPress;
    }
    
    public void getOXY(byte[] buffer){
    	
    	int SpO2 = buffer[26] & 0xFF;
    	int Pulse = buffer[28] & 0xFF;
    	System.out.println("血氧浓度为：  " + SpO2 + "% " +"脉搏为：  " + Pulse +"次/分钟");
    	OXYdata[0] = SpO2;
    	OXYdata[1] = Pulse;
    	
    }
    
    public void getECG(byte[] buffer){
    	System.out.print("心电值： ");
    	
    	int j = 0;
    	for(int i = 0; i < 10; i++){
    		ECG[i] = hTod(buffer[18 + j], buffer[19 + j]);
    		j = j + 2;
    		System.out.print(ECG[i] + " ");
    	}
    	   System.out.println();
    }
    int hTod(byte a, byte b){
    	int ECG0;
    	int a0 = a & 0x0FF;
    	int a1 = a0 / 16 * 16 * 256;
    	int a2 = a0 % 16 * 256;
    	
    	int b0 = b & 0x0FF;
    	
    	ECG0 = a1 + a2 + b0;
    	return ECG0; 
    }
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try{

		}catch(Exception e){
			
		}
	}

}
